import {
  app,
  shell,
  BrowserWindow,
  ipcMain,
  ipcRenderer,
  protocol,
  globalShortcut,
  screen,
  clipboard
} from 'electron'
import { mainWin } from './views'
import api from './core/api'
import pluginManager from './core/plugin-mgr'
import db from './core/db'
import { join, basename } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { exec } from 'child_process'
import fs from 'fs-extra'
import * as utils from './utils'
import plist from 'plist'
import uuid from 'node-uuid'

class App {
  plugins: plugin.Plugin[] = []

  constructor() {
    const gotTheLock = app.requestSingleInstanceLock()
    if (!gotTheLock) {
      app.quit()
      return
    }
    this.main()
  }

  async main() {
    await this.beforeReady()
    await app.whenReady().then(this.onReady)
    await this.onRunning()
  }

  async beforeReady() {
    app.dock.hide()

    // eslint-disable-next-line @typescript-eslint/no-var-requires
    require('@electron/remote/main').initialize()

    //get app info，TOOD：异步获取

    // win状态
    setInterval(async () => {
      global.winState = await utils.getWinState().catch((err) => {
        console.log('get win state error', err)
      })
    }, 500)

    //剪切板工具
    utils.startClipboardWatcher(async () => {
      const copyTime = Date.now()
      const id = uuid.v4()
      const filePlist = clipboard.read('NSFilenamesPboardType')
      const img = clipboard.readImage()

      if (filePlist !== '') {
        try {
          const arr = plist.parse(filePlist) as string[]

          global.clipboardItem = {
            id,
            copyTime,
            type: 'file',
            files: await Promise.all(
              arr.map(
                async (path: string): Promise<IClipboardFileItem> => ({
                  name: basename(path),
                  path,
                  icon: (await app.getFileIcon(path)).toDataURL(),
                  isFile: fs.statSync(path).isFile()
                })
              )
            )
          } as IClipboardItem
        } catch (err) {
          console.log('parse plist error', err)
        }
      } else if (!img.isEmpty()) {
        global.clipboardItem = {
          id,
          copyTime,
          type: 'img',
          content: img.toDataURL()
        } as IClipboardItem
      } else {
        global.clipboardItem = {
          id,
          copyTime,
          type: 'text',
          content: clipboard.readText()
        } as IClipboardItem
      }
    })
  }

  async onReady() {
    //local image
    protocol.interceptFileProtocol('image', (req, callback) => {
      const url = req.url.substr(8)
      callback(decodeURI(url))
    })

    electronApp.setAppUserModelId('com.swiftlc.stools')

    app.on('browser-window-created', (_, window) => {
      optimizer.watchWindowShortcuts(window)
    })

    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })

    //加载配置
    //create window
    mainWin.createWindow()

    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      console.log('ELECTRON_RENDERER_URL', process.env['ELECTRON_RENDERER_URL'])
      mainWin.win.loadURL(process.env['ELECTRON_RENDERER_URL'])
      // mainWindow.loadURL(`http://localhost:5173/`)
    } else {
      mainWin.win.loadFile(join(__dirname, '../renderer/index.html'))
    }

    db.init(join(app.getAppPath(), 'db'))

    api.init()

    await pluginManager.init()

    //托盘图标 TODO

    //快捷键
    if (!globalShortcut.isRegistered('CommandOrControl+I')) {
      globalShortcut.register('CommandOrControl+I', () => {
        mainWin.toggle()
      })
    }
  }

  async onRunning() {
    // ipcMain.on('open-in-terminal', (event, args) => {
    //   //优先使用iterm打开，失败则使用系统默认
    //   exec(`open -a iterm '${args}'`, (err) => {
    //     if (err) {
    //       exec(`open -a Terminal '${args}'`)
    //     }
    //   })
    // })
  }
}

export default new App()

//外开 TODO
// app.removeAsDefaultProtocolClient('app')
// app.setAsDefaultProtocolClient('app', process.execPath, process.argv.slice(1))
// const AGREEMENT_REGEXP = new RegExp(`^app://`)
// //macos监听自定义协议
// app.on('open-url', (_, url) => {
//   console.log('open-url', url)
//   //验证是否为自定义协议
//   if (!AGREEMENT_REGEXP.test(url)) {
//     console.log('非自定义协议')
//     return
//   }
//   //解析参数
//   const u = new URL(url)
//   console.log('自定义协议', u.pathname, u.searchParams.get('name'))
// })
